/*
 * InitServlet.java
 *
 * Created on 2011-7-13 06:07:40 PM
 */
package com.wsleo.jblog;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wsleo.common.utils.ConfigLoader;
import com.wsleo.jblog.freemarker.directive.util.UpperCase;

import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class InitServlet extends FreemarkerServlet {

    private static final long serialVersionUID = -5062396741360110253L;

    @Override
    protected Configuration createConfiguration() {
        Configuration config = super.createConfiguration();
        this.initConfig(config);
        this.initSharedVariables(config);
        return config;
    }
    
    @Override
    protected boolean preTemplateProcess(HttpServletRequest request,
            HttpServletResponse response, Template template, TemplateModel data)
            throws ServletException, IOException {

        SimpleHash sh = (SimpleHash) data;
        sh.put(JConstants.freemarker.REQUEST_CONTEXT, request);
        
        return super.preTemplateProcess(request, response, template, data);
    }


    private void initSharedVariables(Configuration config) {
        config.setSharedVariable("upper", UpperCase.INSTANCE);
    }

    private void initConfig(Configuration config) {
    	try {
			config.setSettings(ConfigLoader.getInstance().getFreemarkerProp());
		} catch (TemplateException e) {
			e.printStackTrace();
		}
    }
}
